package com.hch.datastructure.lru;

import java.util.HashMap;
import java.util.Map;

/**
 * @author HeCongHui
 * @date 2022/6/23 18:32
 */
public class LryCache {

    /**
     * key - node hashmap 定义一个hashmap实现快速查找到相应节点
     */
    private Map<Integer, Node> map;

    private DoubleList cache;
    /**
     * 最大容量
     */
    private int cap;

    public LryCache(int capacity) {

        this.map = new HashMap();
        this.cache = new DoubleList();
        this.cap = capacity;

    }

    /**
     * 将某个key提升到最近使用
     */
    private void makeRecently(int key) {
        Node node = map.get(key);
        cache.remove(node);
        cache.addLast(node);
    }

    /**
     * 添加最近使用的元素
     *
     * @param key
     * @param val
     */
    private void addRecently(int key, int val) {
        Node node = new Node(key, val);
        this.cache.addLast(node);
        this.map.put(key, node);

    }

    /**
     * 删除某一个key
     */

    private void deleteKey(int key) {
        Node remove = this.map.remove(key);
        this.cache.remove(remove);
    }

    /**
     * 删除最久未使用的key
     */
    private void removeLeastRecently() {
        Node node = cache.removeFirst();
        map.remove(node.getKey());
    }

    public void put(int key, int val) {
        if (this.map.containsKey(key)) {
            deleteKey(key);
            addRecently(key, val);
            return;
        }
        if (this.cap == cache.getSize()) {
            removeLeastRecently();
        }
        addRecently(key, val);
    }
}
